package structure.linkedList1;/**
 * Description
 * <p>
 * </p>
 * DATE 2020/4/15.
 *
 * @author cuihao.
 */

import java.util.LinkedList;

/**
 * @program: ch-general
 * @description: 双链表
 * @author: cuihao
 * @create: 2020-04-15 22:41
 **/
public class DoubleLinkedList {

    private Node first;

    private Node last;

    private int size;

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();

        linkedList.get(1);
    }

    public Node get(Integer index) {
        if (index < 0 || index > size - 1) {
            return null;
        }
        if (index < size / 2) {
            Node node = first;
            for (int i = 0; i < index; i++) {
                node = node.next;
            }
            return node;
        } else {
            Node node = last;
            for (int i = size - 1; i > index; i--) {
                node = node.pre;
            }
            return node;
        }
    }

    /**
     * 默认插入尾结点
     *
     * @param value
     */
    public void add(Object value) {
        Node l = last;
        Node newNode = new DoubleLinkedList.Node(value, null, last);
        last = newNode;
        if (last == null) {
            first = newNode;
        } else {
            l.next = newNode;
        }
        size++;
    }

    public void add(Integer index, Object value) {
        if (index < 0 || index > size) {
            return;
        }
        if (index == size) {
            add(value);
        } else {
            Node newNode = new Node(value, null, null);
            // 先获取index节点
            Node pre = get(index);
            Node next = pre.next;
            pre.next = newNode;
            newNode.pre = pre;
            newNode.next = next;
            next.pre = newNode;
        }
    }

    public Object set(Integer index, Object value) {
        if (index < 0 || index > size) {
            return null;
        }
        Node node = get(index);
        Object oldValue = node.value;
        node.value = value;
        return oldValue;
    }

    /**
     * 默认是从首节点删除的
     */
    public void remove(){
        if (first == null) {
            return;
        }
        Node next = first.next;
        if (next == null) {
            first = null;
            last = null;
        } else {
            next.pre = null;
            first = next;
        }
        size--;
    }

    private static class Node {
        private Object value;
        private Node pre;
        private Node next;

        Node(Object value, Node next, Node pre) {
            this.value = value;
            this.next = next;
            this.pre = pre;
        }
    }
}
